//
// Created by yasin on 2024/9/9.
//

#include <iostream>
#include <regex>

#include "http_utils.h"
#include "thirdparty/httplib.h"
#include "rtc_base/thread.h"

namespace ohosrtc::http_utils {

bool ParseUrl(const std::string &url, std::string &host, std::string &path) {
  std::regex urlPattern(R"(https?://([^/]+)(/.*)?)");
  std::smatch matches;
  if (std::regex_search(url, matches, urlPattern)) {
    host = matches[1];
    path = matches[2];
    return true;
  }
  return false;
}

void HttpGet(const std::string &url, HttpSuccessCallback success_cb, HttpFailCallback fail_cb) {
  std::string host;
  std::string path;
  if (!ParseUrl(url, host, path)) {
    if (fail_cb) {
      fail_cb("invalid url");
    }
    return;
  }

  httplib::Client cli(host);
  httplib::Result response = cli.Get(path);
  if (response->status != httplib::StatusCode::OK_200) {
    if (fail_cb) {
      fail_cb(to_string(response.error()));
    }
  } else {
    if (success_cb) {
      success_cb(response->body);
    }
  }
}

void HttpPost(const std::string &host, const std::string &path, HttpSuccessCallback success_cb, HttpFailCallback fail_cb) {
  httplib::Client cli(host);
  httplib::Result response = cli.Post(path);
  if (!response) {
    if (fail_cb) {
      fail_cb("no response");
    }
    return;
  }
  if (response->status != httplib::StatusCode::OK_200) {
    if (fail_cb) {
      fail_cb(to_string(response.error()));
    }
  } else {
    if (success_cb) {
      success_cb(response->body);
    }
  }
}

void HttpDelete(const std::string &host, const std::string &path, HttpSuccessCallback success_cb, HttpFailCallback fail_cb) {
  httplib::Client cli(host);
  httplib::Result response = cli.Delete(path);
  if (response->status != httplib::StatusCode::OK_200) {
    if (fail_cb) {
      fail_cb(to_string(response.error()));
    }
  } else {
    if (success_cb) {
      success_cb(response->body);
    }
  }
}

}